package com.hx.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Component
@Aspect  //代表这是一个切面
@Order(1)
public class TxAdvice {
    /**
     * 通知增强类
     */
    @Pointcut("execution(* com.hx.service.Impl.*.*(..))")
    public void pt() {}
    @Before("pt()")
    protected void begin(JoinPoint joinPoint){

        //可以通连接点获取相应的目标信息
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        List<Object> params=args == null ? null : Arrays.asList(args);
        System.out.println(methodName+"开启事务----参数"+params);
    }

   @AfterReturning(value = "pt()" ,returning = "result")
    protected void commit(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        List<Object> params=args == null ? null : Arrays.asList(args);
        System.out.println(methodName+"提交事务----结果:"+result+"参数:"+params);
       System.out.println("释放资源----");
    }

    @AfterThrowing(value = "pt()" ,throwing = "ex")
    protected void rollback(Exception ex)  {
        System.out.println("回滚事务----"+ex.getMessage());
        System.out.println("释放资源----");
    }

    //@After("pt()")
    protected void release()  {
        System.out.println("释放资源----");
    }




    //环绕增强必须要有返回值
   //@Around("pt()")
    public  Object around(ProceedingJoinPoint pjp){
        Object result=null;
        try {
            String methodName = pjp.getSignature().getName();
            Object[] args = pjp.getArgs();
            List<Object> params=args == null ? null : Arrays.asList(args);
            System.out.println(methodName+"开启事务----参数:"+params);
            //调用目标方法
            result =pjp.proceed();

            System.out.println(methodName+"提交事务----结果:"+result+"参数:"+params);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("回滚事务----"+throwable.getMessage());
        }finally {
            System.out.println("释放资源----");
        }
        return result;
    }

}
